import HandSonGrid from "../HandSonGrid";
import { nanoid10 } from "../../../tools/Tools";
import CellCoords from "../../../lib/tmp/3rdparty/walkontable/src/cell/coords";
import { message } from "antd";
import _ from "lodash";
import { createCellPos } from "../Tools";
export default class GridService {
    context;
    constructor(context) {
        this.context = context;
    }
    get headerService() {
        return this.context.headerService;
    }
    get hot() {
        return this.context.hot;
    }
    get hyper() {
        return this.context.hyper;
    }
    get formulaService() {
        return this.context.formulaService;
    }
    get tagService() {
        return this.context.tagService;
    }
    //重置表格数据
    resetGridData(gridData) {
        this.context.data = gridData.data;
        this.context.headerData = gridData.header;
        this.context.cellMetaData = gridData.cellsMeta;
        this.context.tableConfig = gridData.tableConfig;
    }
    destroy() {
        this.context = null;
    }
    // 查询单元格配置信息
    getCellMateDataByRowAndProp(row, col, data) {
        if (!data) {
            data = this.context.cellMetaData;
        }
        let matchItem;
        for (let i = 0; i < data?.length; i++) {
            const cellMeta = data[i];
            if (row === cellMeta["row"] && col === cellMeta["col"]) {
                matchItem = cellMeta;
                break;
            }
        }
        return matchItem || {};
    }
    /**
     * 根据 GridData 生成 rmap,cmap字典映射
     */
    createMapByData(data) {
        console.log("🚀 ~ GridService ~ createMapByData ~ data:", data)
        const maps = {};
        for (let i = 0; i < data.length; i++) {
            const row = data[i];
            for (let j = 0; j < row.length; j++) {
                // 跳过 0行，0列，最后一个配置列
                if (i !== 0 && j !== 0 && j !== row.length - 1) {
                    const value = row[j];
                    const key = data[i][0] + "|||" + data[0][j]; //rmap|||cmap
                    maps[key] = value;
                }
            }
        }
        return maps;
    }
    /**
     * 清空所有cellMeta功能config以及样式config
     */
    resetAllCellMetaConfig() {
        // debugger;
        const columnMetaArr = this.hot.getCellsMeta();
        for (let i = 0, length = columnMetaArr.length; i < length; i++) {
            const { col, row, instance, prop, visualCol, visualRow } = columnMetaArr[i];
            columnMetaArr[i] = {
                col: visualCol,
                instance: instance,
                prop: prop,
                row: visualRow,
                visualCol: visualCol,
                visualRow: visualRow,
            };
        }
    }
    /**
     * 清空单元格自定义样式配置信息
     */
    resetAllCellsMetaStyleConfig() {
        const columnMetaArr = this.hot.getCellsMeta();
        for (let i = 0, length = columnMetaArr.length; i < length; i++) {
            const columnMeta = columnMetaArr[i];
            delete columnMeta.style;
            delete columnMeta.custom;
        }
    }
    //查询行配置信息
    getRowMeteDataByRow(row, data = null) {
        if (row > -1) {
            let config;
            if (data) {
                //CpasTable限制最少一行,所以不需要判断是否存在
                config = data[row]?.[data[0].length - 1];
            }
            else {
                config = this.context?.data?.[row]?.[this.headerService.lastHeader];
            }
            return config ? JSON.parse(config) : {};
        }
        else {
            return null;
        }
    }
    //查询列配置信息
    getColumnMetaDataByColumn(row, col) {
        const textRender = {
            renderer: "cpasDefaultRender",
        };
        const numbericRender = {
            renderer: "cpasNumericRender",
            numericFormat: {
                pattern: "0,00.00", //默认千分位符
            },
        };
        const header_item = this.headerService.headerColumn[col];
        const cellType = header_item?.config?.type;
        if (row > 0 && cellType === "numeric") {
            return {
                columnKey: header_item?.key,
                ...numbericRender,
                ...header_item.config,
            };
        }
        else {
            return {
                columnKey: header_item?.key,
                ...textRender,
                ...header_item?.config,
            };
        }
    }
    /**
     * 获取cmap根据key
     */
    getCmapByKey(key, headerColumn) {
        for (let i = 0; i < headerColumn.length; i++) {
            const header = headerColumn[i];
            if (header.key === key) {
                return header.cmap;
            }
        }
        return null;
    }
    /**
     * 根据rmap,cmap返回坐标
     */
    getCellCoordsByRmapCmap(rmap, cmap) {
        const row = this.getRowIndexByRmap(rmap);
        const col = this.getColumnIndexByCmap(cmap);
        if (row && col) {
            return new CellCoords(row, col);
        }
        else {
            return null;
        }
    }
    /**
     * 根据 坐标返回rmap,cmap
     */
    getMapsByCoords(data, coords) {
        const { row, col } = coords;
        return {
            rmap: this.getAllRowsMaps(data)[row - 1 < 0 ? 0 : row - 1],
            cmap: data[0][col],
        };
    }
    /**
     * 获取所有行的rmap映射信息
     */
    getAllRowsMaps(data) {
        let result;
        if (data) {
            result = [...data.map((item) => item[0])];
        }
        else {
            result = this.hot.getDataAtCol(0);
        }
        result.shift();
        return result;
    }
    /**
     * 根据行列索引获取值
     * @param rmap
     * @param cmap
     */
    getCellValueByRmapCmap(rmap, cmap) {
        const row = this.getRowIndexByRmap(rmap);
        const col = this.getColumnIndexByCmap(cmap);
        if (row && col) {
            return this.hot.getDataAtCell(row, col);
        }
        else {
            return 0;
        }
    }
    /**
     * 获取指定rmap的索引号
     * @param rmap
     */
    getRowIndexByRmap(rmap) {
        const rowMaps = this.getAllRowsMaps();
        const match = rowMaps.indexOf(rmap);
        return match > -1 ? match + 1 : null;
    }
    /**
     * 获取cmap的索引号
     * @param cmap
     */
    getColumnIndexByCmap(cmap) {
        const colMaps = this.headerService.getAllHeaderMap();
        const match = colMaps.indexOf(cmap);
        return match > -1 ? match + 1 : null;
    }
    removeRows(currentRange) {
        const dataCount = this.context.hot.getData().length;
        for (let i = 0; i < currentRange.length; i++) {
            const range = currentRange[i];
            let from_row = range.from.row;
            let to_row = range.to.row;
            if (from_row === 0) {
                message.info("不能删除映射行");
                break;
            }
            if (from_row < 0) {
                from_row = 1;
            }
            let amount = to_row - from_row + 1;
            if (amount === dataCount - 1) {
                message.info("请至少保留一行");
                break;
            }
            this.hot.alter("remove_row", from_row, amount);
        }
        this.context.data = this.context.hot.getSourceData();
        //刷新公式
        //this.formulaService.refreshAllPolymericRow();
        //this.formulaService.refreshAllPolymericColumn();
        //刷新公式@todo迁移后台
        this.formulaService.refreshAllPolymeric(true);
    }
    /**
     * 刷新cellsMeta信息, 此处刷新的是 json中的 cellsMeta信息
     *  row 刷新行 , column 刷新列
     *  operation add minus
     */
    refreshCellsMeta(type, coordsInfo, cellsMeta, isCopyCellsMeta = true) {
        const { row_start, row_offset, col_start, col_offset, operation } = coordsInfo;
        if (type === "row") {
            return this.refreshCellsMetaByRow(operation, row_start, row_offset, cellsMeta, isCopyCellsMeta);
        }
        else if (type === "column") {
            return this.refreshCellsMetaByColumn(operation, col_start, col_offset, cellsMeta, isCopyCellsMeta);
        }
        else {
            return cellsMeta;
        }
    }
    refreshCellsMetaByRow(operation, row_start, row_offset, cellsMeta, isCopyCellsMeta) {
        //操作副本
        const cloneCellsMeta = _.cloneDeep(cellsMeta);
        //母行的元数据
        let mainRowMeta = [];
        cloneCellsMeta.forEach((cellMeta, index) => {
            if (cellMeta.row === row_start) {
                mainRowMeta.push(cellMeta);
            }
            if (!operation || operation === "add") {
                if (cellMeta.row > row_start) {
                    cellMeta.row += row_offset;
                }
            }
            else if (operation === "minus") {
                if (cellMeta.row > row_start) {
                    cellMeta.row -= row_offset;
                }
            }
        });
        //动态拷贝的样式属性
        const copyCellMetas = [];
        if (isCopyCellsMeta) {
            const start_copy_index = row_start + 1;
            const end_copy_index = row_start + row_offset;
            for (let row = start_copy_index; row <= end_copy_index; row++) {
                for (let j = 0; j < mainRowMeta.length; j++) {
                    const mainMeta = mainRowMeta[j];
                    if (mainMeta.custom) {
                        copyCellMetas.push({
                            row: row,
                            col: mainMeta.col,
                            custom: mainMeta.custom,
                        });
                    }
                }
            }
        }
        return [...cloneCellsMeta, ...copyCellMetas];
    }
    refreshCellsMetaByColumn(operation, col_start, col_offset, cellsMeta, isCopyCellsMeta) {
        //操作副本
        const cloneCellsMeta = _.cloneDeep(cellsMeta);
        //母列元数据
        let mainColumnMeta = [];
        cloneCellsMeta.forEach((cellMeta) => {
            if (cellMeta.col === col_start) {
                mainColumnMeta.push(cellMeta);
            }
            if (!operation || operation === "add") {
                if (cellMeta.col > col_start) {
                    cellMeta.col += col_offset;
                }
            }
            else if (operation === "minus") {
                if (cellMeta.col > col_start) {
                    cellMeta.col -= col_offset;
                }
            }
        });
        //动态拷贝的样式属性
        const copyCellMetas = [];
        if (isCopyCellsMeta) {
            const start_copy_index = col_start + 1;
            const end_copy_index = col_start + col_offset;
            for (let col = start_copy_index; col <= end_copy_index; col++) {
                for (let j = 0; j < mainColumnMeta.length; j++) {
                    const mainMeta = mainColumnMeta[j];
                    if (mainMeta.custom) {
                        copyCellMetas.push({
                            row: mainMeta.row,
                            col: col,
                            custom: mainMeta.custom,
                        });
                    }
                }
            }
        }
        return [...cloneCellsMeta, ...copyCellMetas];
    }
    /**
     * 根据key获取cmap值
     */
    /**
     * 自动赋值cmap逻辑
     * 如果传递 lastHeaderColumn , 则需要对比是否要更新cmap。 不传递默认全部覆盖
     */
    autoFillCmap(lastHeaderColumn) {
        //最新的headerColumn
        const headerColumn = this.headerService.headerColumn;
        const updateData = [];
        for (let i = 0; i < headerColumn.length; i++) {
            if (i === 0 || i === this.headerService.lastHeader)
                continue;
            if (lastHeaderColumn) {
                const key = headerColumn[i]["key"];
                //获取当前cmap值
                const currentMap = this.hot.getDataAtCell(0, i);
                //旧cmap值
                const oldMap = this.getCmapByKey(key, lastHeaderColumn);
                if (currentMap === "" || currentMap === oldMap || oldMap === null) {
                    const computedMap = headerColumn[i]["cmap"] || "";
                    updateData.push([0, i, computedMap || ""]);
                    this.context.data[0][i] = computedMap || "";
                }
            }
            else {
                updateData.push([0, i, headerColumn[i]["cmap"] || ""]);
            }
        }
        this.hot.setDataAtCell(updateData);
    }
    /**
     * 获取单元格配置信息
     */
    getCellMetaByRowCol(row, col, cellMetas) {
        if (cellMetas) {
            for (let i = 0, length = cellMetas.length; i < length; i++) {
                const cellMeta = cellMetas[i];
                if (row === cellMeta["row"] && col === cellMeta["col"]) {
                    return cellMeta;
                }
            }
        }
        return this.hot.getCellMeta(row, col);
    }
    /**
     * 新增航
     * @param type top , bottom
     * @param isCopy 是否拷贝选中行属性
     * @param insertIndex 插入的索引其实位置
     * @param currentGroupKeyColumn 行分组key
     * @param insertCount 插入的数量
     */
    async addRow(type, isCopy, insertIndex, currentGroupKeyColumn, insertCount, isStopRefreshFormula) {
        const count = insertCount || 1;
        const currentCountRows = this.context.hot.countRows();
        const menuToolRef = this.context.menuToolRef.current;
        if (currentCountRows + count >
            HandSonGrid.MAX_ROWS + HandSonGrid.MAX_ROWS_OFFSET) {
            menuToolRef.showErrorNotify(`添加行失败, 当前表格限制最大行数为${HandSonGrid.MAX_ROWS}`);
            return;
        }
        const gridData = this.context.data;
        let handle_row = gridData[type === "top" ? insertIndex : insertIndex - 1];
        if (!handle_row) {
            handle_row = gridData[1];
        }
        const handle_row_config = handle_row[this.headerService.lastHeader];
        const handle_row_config_obj = JSON.parse(handle_row_config);
        if (handle_row_config_obj?.r_polymeric) {
            //上方插入行需要带上tag
            if (type === "top") {
                let prev_handle_row = gridData.length < 3
                    ? gridData[insertIndex]
                    : gridData[insertIndex - 1];
                if (prev_handle_row && prev_handle_row.length) {
                    const prev_handle_row_config = prev_handle_row[this.headerService.lastHeader];
                    const prev_handle_row_config_obj = JSON.parse(prev_handle_row_config);
                    if (prev_handle_row_config_obj?.r_tag) {
                        handle_row_config_obj["r_tag"] = prev_handle_row_config_obj?.r_tag;
                    }
                    else if (prev_handle_row_config_obj?.r_polymeric?.tags) {
                        handle_row_config_obj["r_tag"] =
                            prev_handle_row_config_obj?.r_polymeric?.tags;
                    }
                }
            }
            //插入行手动删除行聚合标签
            delete handle_row_config_obj.r_polymeric;
        }
        //插入行手动删除行运算符标签
        if (handle_row_config_obj?.operator_r) {
            delete handle_row_config_obj.operator_r;
        }
        if (handle_row_config_obj?.formula) {
            delete handle_row_config_obj.formula;
        }
        this.hot.suspendRender();
        this.hot.alter("insert_row", insertIndex, count);
        //TODO,如果是分组行 暂时未开启分组功能。如果开启分组功能，这里需要支持批量增加逻辑
        // if (handle_row_config_obj.r_tag) {
        //   //组名称规则 以 - 进行分割
        //   const groupTag = handle_row_config_obj.r_tag.find(
        //     (item) => item.indexOf("组") > -1
        //   );
        //   if (groupTag) {
        //     const groupName = groupTag.split("-");
        //
        //     this.hot.setDataAtCell(
        //       insertIndex,
        //       currentGroupKeyColumn,
        //       groupName[0]
        //     );
        //     this.hot.setCellMeta(insertIndex, currentGroupKeyColumn, "r", 2);
        //   }
        // }
        const newGridData = this.hot.getData();
        const insertRows = [];
        // 找出调整后的列, 拼接调整后的公式.
        const headerColumn = this.headerService.headerLevelData.headerColumn;
        const tzh = [];
        headerColumn.forEach((item, index) => {
            const { tzType, p_exclude, c_polymeric } = item.config;
            // 提取调整后需要生成公式的列
            if (tzType && tzType === "tzh" && !p_exclude && !c_polymeric) {
                tzh.push(index);
            }
        });
        for (let i = insertIndex; i < count + insertIndex; i++) {
            console.log(i);
            insertRows.push(i);
            const newRow = newGridData[i];
            const base_config = {
                rId: nanoid10(),
            };
            const clone_handle_row_config_obj = { ...handle_row_config_obj };
            //拷贝行属性
            if (isCopy) {
                if (clone_handle_row_config_obj.r_polymeric) {
                    delete clone_handle_row_config_obj.r_polymeric;
                }
                const merge_copy_data = JSON.stringify({
                    ...clone_handle_row_config_obj,
                    ...base_config,
                });
                if (newRow)
                    newRow[this.headerService.lastHeader] = merge_copy_data;
                // this.hot.setDataAtCell(
                //   i,
                //   this.headerService.lastHeader,
                //   merge_copy_data
                // );
            }
            else {
                if (newRow)
                    newRow[this.headerService.lastHeader] = JSON.stringify(base_config);
            }
            const currentRowIndex = insertIndex + i;
            // 补充调整后公式
            tzh.forEach((item) => {
                newRow[item] = `=IFERROR(SUM(${createCellPos(item - 2)}${currentRowIndex},${createCellPos(item - 1)}${currentRowIndex}),0)`;
            });
        }
        //优:保持context持有的data保持数据同步，因为gridHooks中会用到
        this.context.data = newGridData;
        this.hot.updateData(newGridData);
        this.hot.resumeRender();
        // TODO 这里改造成利用work异步计算，将0位自动补成公式. 异步涉及共同修改相同资源问题。需要进异步设计。暂时不考虑
        //this.formulaService.refreshAllPolymericRow();
        //this.formulaService.refreshAllPolymericColumn();
        //刷新公式@todo迁移后台
        if (!isStopRefreshFormula) {
            await this.formulaService.refreshAllPolymeric();
        }
        this.context.tagService.refreshTagColumn(this.context, insertRows);
    }
    //根据columnIndex数组删除data中的多列数据
    removeColumnsData(columnIndexs, iGridData) {
        const data = iGridData.data;
        const new_data = data.map((item) => {
            const new_item = item.filter((_, index) => {
                return !columnIndexs.includes(index);
            });
            return new_item;
        });
        return new_data;
    }
    removeColumn(key, isRefresh = true, header) {
        const headJson = header || this.headerService.headJson;
        let nodeInfo = this.headerService.findNodeByKeyAndParent(key, headJson, headJson);
        console.log(this.headerService.getLeafLength(nodeInfo.pNode));
        // 有一个隐藏配置列
        if (this.headerService.getLeafLength(nodeInfo.pNode) === 2) {
            this.context.menuToolRef.current.showErrorNotify("请至少保留一个表头");
            return;
        }
        const currentNode = nodeInfo.pNode["children"]
            ? nodeInfo.pNode["children"][nodeInfo.index]
            : nodeInfo.pNode[nodeInfo.index];
        const remove_column_index = this.headerService.getColumnIndexByParentNode(currentNode, headJson);
        console.log(remove_column_index[0], remove_column_index.length);
        let isChild = true;
        if ((nodeInfo.pNode["children"] && nodeInfo.pNode["children"].length !== 1) ||
            (!nodeInfo.pNode["children"] && nodeInfo.pNode.length !== 1)) {
            isChild = false;
        }
        if (nodeInfo.pNode["children"]) {
            nodeInfo.pNode["children"].splice(nodeInfo.index, 1);
            if (nodeInfo.pNode["children"].length === 0) {
                delete nodeInfo.pNode["children"];
            }
        }
        else {
            nodeInfo.pNode.splice(nodeInfo.index, 1);
        }
        if (header) {
            return this.headerService.headerComputeData(header);
        }
        else {
            this.headerService.headerCompute(this.headerService.headJson, false);
        }
        if (isRefresh) {
            this.hansonRemoveColumn(remove_column_index, isChild);
        }
    }
    deepCopyArray(array) {
        var copy = [];
        for (var i = 0; i < array.length; i++) {
            if (Array.isArray(array[i])) {
                copy[i] = this.deepCopyArray(array[i]); // 递归处理子数组
            }
            else {
                copy[i] = array[i];
            }
        }
        return copy;
    }
    hansonRemoveColumn(remove_column_index, isChild) {
        if (!isChild) {
            const currentSourceData = this.deepCopyArray(this.hot.getSourceData());
            // 这种方式在复合表头，并且为最后一列时存在bug, 会造成配置列被删除！！！
            // 2024年5月30日13:42:01
            // this.hot.alter(
            //   "remove_col",
            //   remove_column_index[0],
            //   remove_column_index.length
            // );
            const changes = this.hyper.removeColumns(0, [
                remove_column_index[0],
                remove_column_index.length,
            ]);
            console.log(changes);
            //刷新公式@todo迁移后台
            //不能去掉, 否则会造成cellsMeta错乱.由于隐藏行列
            const removeColumnData = this.hyper.getSheetSerialized(0);
            this.context.data = removeColumnData;
            this.hot.updateData(removeColumnData); //loadData会导致cellMeta丢失，改为updateData方法调用。@dingxiaofei 2024-09-03
            this.formulaService.refreshAllPolymeric();
        }
        else {
            //不能去掉, 否则会造成cellsMeta错乱.由于隐藏行列
            this.hot.loadData(this.hot.getSourceData());
        }
        // if (this.context.props.type === "ds") {
        //   this.autoFillCmap(null);
        // }
        this.hiddenColumnAndRow();
        //删除后默认恢复到第一个列
        this.headerService.selectHeaderByIndex([1, 1, -1], this.headerService.headerColumn[1].key);
    }
    /**
     * 重新生成行id
     */
    resetRowsId(data) {
        const copyData = [...data];
        for (let i = 0; i < copyData.length; i++) {
            const row = copyData[i];
            const row_config_str = row[row.length - 1];
            const config = JSON.parse(row_config_str);
            config["rId"] = nanoid10();
            row[row.length - 1] = JSON.stringify(config);
        }
        return copyData;
    }
    /**
     * 重新生成表,列,行,单元格id
     * @param type
     * @param isCopy
     * @param columnKey
     */
    resetCpasTableId(gridData) {
        const { header, data, cellsMeta, tableConfig, zlTableConfig } = gridData;
        const newHeader = this.headerService.resetHeaderId(header);
        const newData = this.resetRowsId(data);
        if (zlTableConfig) {
            return {
                header: newHeader,
                data: newData,
                cellsMeta,
                tableConfig,
                zlTableConfig,
            };
        }
        else {
            return {
                header: newHeader,
                data: newData,
                cellsMeta,
                tableConfig,
            };
        }
    }
    /**
     * 根据range范围获取数据
     */
    getDataByRange(selectedRanges) {
        const lastHeader = this.headerService.lastHeader;
        //rangeData为三维数组, 第一维为range, 第二维为行, 第三维为列.如果要使用该数据,需要遍历
        const rangeData = [];
        if (selectedRanges.length > 0) {
            for (const range of selectedRanges) {
                const startRow = range.from.row < 1 ? 1 : range.from.row;
                const starColumn = range.from.col < 1 ? 1 : range.from.col;
                const endRow = range.to.row < 1 ? 1 : range.to.row;
                let endColumn = range.to.col < 1 ? 1 : range.to.col;
                endColumn = endColumn >= lastHeader ? lastHeader - 1 : endColumn;
                const selectedData = this.hot.getData(startRow, starColumn, endRow, endColumn);
                console.log("Selected data:", selectedData);
                rangeData.push(selectedData);
            }
        }
        return rangeData;
    }
    async addColumn(type, isCopy, columnKey, columnInfo = {
        columnName: "",
        isReadOnly: false,
        isRuntime: false,
        columnType: "numeric",
    }, isNeedToRefreshFormula = true) {
        const { columnName, isReadOnly, isRuntime, columnType, width } = columnInfo;
        const insertCount = 1; //列目前仅支持单个添加
        const currentColumnCount = this.headerService.headerColumn.length;
        const menuToolRef = this.context.menuToolRef.current;
        if (currentColumnCount + insertCount >
            HandSonGrid.MAX_COLUMNS + HandSonGrid.MAX_COLUMNS_OFFSET) {
            menuToolRef.showErrorNotify(`添加列失败, 当前表格限制最大列数为${HandSonGrid.MAX_COLUMNS}`);
            return;
        }
        let nodeInfo = this.headerService.findNodeByKeyAndParent(columnKey, this.headerService.headJson, this.headerService.headJson);
        console.log(nodeInfo);
        const { levelData, coords } = this.headerService.getNodeIndexByKey(columnKey);
        const newColumnName = columnName ? columnName : "新增列" + Date.now();
        const key = nanoid10();
        let newColumn = {
            key: key,
            label: newColumnName,
            config: {
                type: columnType,
            },
        };
        if (isReadOnly) {
            newColumn.config["readOnly"] = true;
        }
        if (isRuntime) {
            newColumn.config["isRuntime"] = true;
        }
        if (width) {
            newColumn.config["width"] = width;
        }
        const insert_index = type === "left" ? nodeInfo.index : nodeInfo.index + 1;
        if (insert_index === 0 && type === "left") {
            message.info("不能在主键左侧插入列");
            return;
        }
        const currentIndex = coords.col;
        if (isCopy) {
            const copyNode = _.cloneDeep(nodeInfo);
            //不拷贝期间类型
            delete copyNode.config.groupId;
            delete copyNode.config.timeColumn;
            // debugger;
            newColumn.config = {
                ...newColumn.config,
                ...copyNode.config,
            };
        }
        // debugger;
        if (type === "child") {
            const currentNode = nodeInfo.pNode["children"]
                ? nodeInfo.pNode["children"][nodeInfo.index]
                : nodeInfo.pNode[nodeInfo.index];
            if (!currentNode["children"]) {
                currentNode["children"] = [];
            }
            //如果已经存在子列，则向子列的右侧插入
            if (currentNode["children"].length > 0) {
                type = "right";
            }
            currentNode["children"].push(newColumn);
        }
        else if (nodeInfo.pNode.children) {
            nodeInfo.pNode.children.splice(insert_index, 0, newColumn);
        }
        else {
            nodeInfo.pNode.splice(insert_index, 0, newColumn);
        }
        const lastHeaderColumn = this.headerService.headerColumn;
        this.headerService.headerCompute(this.headerService.headJson, false);
        await this.hansonAddColumn(type, key, newColumn, currentIndex, lastHeaderColumn, isNeedToRefreshFormula);
    }
    async hansonAddColumn(type, newColumnKey, newColumn, currentIndex, lastHeaderColumn, isNeedToRefreshFormula) {
        //cpas coords 非原生handson坐标
        let data;
        this.hot.batch(() => {
            const { levelData, coords } = this.headerService.getNodeIndexByKey(newColumnKey);
            const new_column_index = this.getColumnIndexByColumnKey(newColumnKey);
            let handle_index = 0;
            //进行hanson 更新
            data = this.hot.getSourceData();
            if (type !== "child") {
                handle_index = new_column_index;
                this.hot.alter("insert_col", new_column_index, 1);
                data = this.hot.getSourceData();
                const columnType = newColumn && newColumn?.config?.type ? newColumn?.config?.type : "";
                for (let i = 0; i < data.length; i++) {
                    // 使用setDataAtCell方法，将新列数据设置到指定的单元格
                    const rows = data[i];
                    const lastRowConfig = rows && rows[rows.length - 1]
                        ? JSON.parse(rows[rows.length - 1])
                        : {};
                    const config = rows[rows.length - 1];
                    if (i > 0 &&
                        !lastRowConfig?.r_polymeric &&
                        columnType === "numeric") {
                        this.hot.setDataAtCell(i, new_column_index, 0);
                        data[i][new_column_index] = 0;
                    }
                }
            }
            else {
                handle_index = currentIndex;
            }
            // debugger;
            //如果是披露表类型，增加列自动增加cmap值
            if (this.context.props.type === "ds") {
                // this.hot.setDataAtCell(0, handle_index, newColumn.label);
                if (newColumn?.label !== "行标签") {
                    this.autoFillCmap(lastHeaderColumn);
                }
            }
            this.hiddenColumnAndRow();
            this.headerService.selectHeaderByIndex([handle_index, handle_index, coords.row], newColumnKey);
            //this.formulaService.refreshAllPolymericRow();
            //this.formulaService.refreshAllPolymericColumn();
        });
        //不能去掉, 否则会造成cellsMeta错乱.由于隐藏行列,注意隐藏行列一定要在这个上面
        this.context.reloadTableDataWithStyle(data);
        if (isNeedToRefreshFormula) {
            // TODO 这里优化成指定列刷新
            await this.formulaService.refreshAllPolymeric(true);
        }
    }
    getColumnIndexByColumnKeyData(columnKey, headerColumn) {
        return headerColumn.findIndex((item) => item.key === columnKey);
    }
    //列头映射, 根据列名称得出该列的index位置
    getColumnIndexByColumnKey(columnKey) {
        return this.headerService.headerColumn.findIndex((item) => item.key === columnKey);
    }
    /**
     * 多行移动到一个位置
     */
    moveRowsToTarget(rowNumbers, targetRowNumber) {
        const isMovePossible = this.context.manualRowMovePlugin.isMovePossible(rowNumbers, targetRowNumber);
        if (!isMovePossible) {
            this.context.menuToolRef.current.showErrorNotify("移动失败，目标位置无效");
        }
        this.context.manualRowMovePlugin.moveRows(rowNumbers, targetRowNumber);
    }
    /**
     * 批量多行移动
     */
    moveRowsByDirection(moveRows, direction) {
        // this.hot.suspendRender();
        this.getSyncHyperData();
        const sheetId = this.hyper.getSheetId("main");
        let targetRows = []; //目标行
        for (let i = 0; i < moveRows.length; i++) {
            const moveRow = moveRows[i];
            this.hyper.moveRows(sheetId, moveRow.index, 1, direction === "top" ? moveRow.target : moveRow.target + 1);
            this.context.manualRowMovePlugin.moveRow(moveRow.index, moveRow.target);
            if (!targetRows.includes(moveRow.target)) {
                targetRows.push(moveRow.target);
            }
        }
        //行上移最后一行是行聚合标签需要把移动的行带上行标签
        const { data, isRefreshFormula } = this.addTagForData(direction, this.context.hyper.getAllSheetsSerialized()["main"], targetRows);
        //必须触发一次，否则不会刷新cellMeta值;
        // this.hot.render();
        // console.log(this.hyper.getAllSheetsSerialized());
        // this.hot.loadData(this.hyper.getAllSheetsSerialized()["main"]);
        // 物理移动并刷新cellMeta
        this.loadDataAndRefreshCellMeta(data, isRefreshFormula);
    }
    /**
     * 给移动的行数据添加标签
     * @param direction 方向
     * @param data data数据
     * @param targetRows 目标行
     * @returns
     */
    addTagForData(direction, data, targetRows) {
        let isRefreshFormula = false;
        if (direction === "top") {
            console.log("direction");
            const maxTargetRow = Math.max(...targetRows);
            const handleRow = data[maxTargetRow + 1];
            const rMap = handleRow ? handleRow[0] : "";
            if (rMap.startsWith("行|聚合")) {
                //找到行标签tag
                const minTargetRow = Math.min(...targetRows);
                const handleRow = data[minTargetRow - 1];
                if (handleRow && handleRow.length) {
                    const handleRowConfig = handleRow[this.headerService.lastHeader];
                    const handleRowConfigObj = JSON.parse(handleRowConfig);
                    const rTag = handleRowConfigObj?.r_tag;
                    if (rTag) {
                        //给目标行打行标签
                        isRefreshFormula = true;
                        for (let i = 0; i < targetRows.length; i++) {
                            const rowData = data[targetRows[i]];
                            const rowConfig = rowData[this.headerService.lastHeader];
                            const rowConfigObj = JSON.parse(rowConfig);
                            data[targetRows[i]][this.headerService.lastHeader] =
                                JSON.stringify({
                                    ...rowConfigObj,
                                    r_tag: rTag,
                                });
                        }
                    }
                }
            }
        }
        else {
            console.log("direction");
            const maxTargetRow = Math.min(...targetRows);
            const handleRow = data[maxTargetRow - 1];
            const rMap = handleRow ? handleRow[0] : "";
            if (rMap && rMap.startsWith("行|聚合")) {
                //找到行标签tag
                isRefreshFormula = true;
                for (let i = 0; i < targetRows.length; i++) {
                    const row = targetRows[i];
                    const rowData = data[row];
                    const rowConfig = rowData[this.headerService.lastHeader];
                    let rowConfigObj = JSON.parse(rowConfig);
                    delete rowConfigObj.r_tag;
                    data[row][this.headerService.lastHeader] = JSON.stringify({
                        ...rowConfigObj,
                    });
                }
            }
        }
        return {
            data,
            isRefreshFormula,
        };
    }
    /**
     * sync hyper data
     */
    getSyncHyperData() {
        const sourceData = this.hot.getSourceData();
        this.hyper.setSheetContent(0, sourceData);
    }
    /**
     * 将visualIndex cellMeta转换为物理index
     */
    convertVisualIndexToPhysicalIndex() {
        const changeCellMetas = [];
        for (let i = 0; i < this.context.data.length; i++) {
            const row = this.context.data[i];
            for (let j = 0; j < row.length; j++) {
                //该函数取的是visualIndex
                const item = this.hot.getCellMeta(i, j);
                // if (item.custom) {
                changeCellMetas.push({
                    ...item,
                    row: item.visualRow,
                    col: item.visualCol,
                    // custom: { ...item.custom },
                });
                // }
            }
        }
        this.context.cellMetaData = [...changeCellMetas];
    }
    /**
     * 刷新visualIndex 到physicalIndex 的加载
     */
    loadDataAndRefreshCellMeta(data, isRefreshFormula) {
        this.context.actionType = {
            action: "load",
            index: 0,
            amount: 0,
        };
        this.convertVisualIndexToPhysicalIndex();
        this.context.data = data;
        this.hot.loadData(data);
        isRefreshFormula && this.formulaService.refreshAllPolymeric(true); //刷新标签
        this.context.actionType = {
            action: "",
            index: 0,
            amount: 0,
        };
    }
    /**
     * 根据方向接收range返回需要移动的行,以及根据移动的值进行单元格范围划选数据
     * @param range
     * @param direction
     */
    getMoveRows = (range, direction) => {
        const computedMovesRows = [];
        let computedAfterMoveRange = [];
        const { from, to } = range;
        const startRow = from.row; //起始行
        const startCol = from.col;
        const endRow = to.row;
        const endCol = to.col;
        const a_coords = range.getAll();
        const topRow = 1;
        const bottomRow = this.context.hot.countRows() - 1;
        //如果队头行为1，则整个range不需要在移动 , 或者队尾行为最后一行，则整个range不需要在移动
        if (startRow === topRow && direction === "top") {
            return { computedAfterMoveRange, computedMovesRows };
        }
        if (endRow === bottomRow && direction === "bottom") {
            return { computedAfterMoveRange, computedMovesRows };
        }
        if (direction === "top") {
            for (let j = 0; j < a_coords.length; j++) {
                const coords = a_coords[j];
                const { row, col } = coords;
                if (row === 0) {
                    continue;
                }
                const computedRow = this.getTargetRowIndex(direction, row);
                computedMovesRows.push({
                    index: row,
                    target: computedRow,
                });
            }
        }
        else {
            for (let j = a_coords.length - 1; j >= 0; j--) {
                const coords = a_coords[j];
                const { row, col } = coords;
                if (row === 0) {
                    continue;
                }
                const computedRow = this.getTargetRowIndex(direction, row);
                computedMovesRows.push({
                    index: row,
                    target: computedRow,
                });
            }
        }
        //如果成功移动,则刷新起始行和结束行位置
        computedAfterMoveRange = [
            direction === "top" ? startRow - 1 : startRow + 1,
            startCol,
            direction === "top" ? endRow - 1 : endRow + 1,
            endCol,
        ];
        return {
            computedAfterMoveRange,
            computedMovesRows,
        };
    };
    //计算移动后的目标行位置
    getTargetRowIndex = (direction, row) => {
        let computedRow = 0;
        if (direction === "top") {
            computedRow = row - 1;
        }
        else {
            computedRow = row + 1;
        }
        return computedRow;
    };
    /**
     * 获取范围中的去重行,列
     */
    getRangeRowsAndColumn(range) {
        const rows = new Set();
        const columns = new Set();
        for (let i = 0; i < range.length; i++) {
            const rangeItem = range[i];
            const all = rangeItem.getAll();
            for (let j = 0; j < all.length; j++) {
                const cell = all[j];
                rows.add(cell.row);
                columns.add(cell.col);
            }
        }
        return {
            rows: Array.from(rows),
            cols: Array.from(columns),
        };
    }
    /**
     * 设置缩进到单元格属性
     */
    setRetractToCell(retract, currentRange) {
        for (let i = 0; i < currentRange.length; i++) {
            const rangeAllCell = currentRange[i].getAll();
            for (let j = 0; j < rangeAllCell.length; j++) {
                const coords = rangeAllCell[j];
                const cellMeta = this.hot.getCellMeta(coords.row, coords.col);
                //只有文本类可以调整缩进
                if (cellMeta.type === "text") {
                    this.setCellMetaCustomInfo(coords.row, coords.col, "r", retract);
                    // const renderFunc = hotRef.current.getCellRenderer(
                    //   coords.row,
                    //   coords.col
                    // );
                    // renderFunc();
                }
            }
        }
        this.hot.render();
    }
    /**
     * 设置单元格文本加粗
     * type : 1 常规  2加粗
     */
    setCellFontBold(type, currentRange) {
        this.setCellConfig({ bl: type }, currentRange);
    }
    /**
     * 设置单元格字形
     * type : 1 常规  2 斜体
     */
    setCellFontStyle(type, currentRange) {
        this.setCellConfig({ it: type }, currentRange);
    }
    /**
     * 增加减少小数位
     * type: add 增加小数位 ， minus 减少小数位
     */
    setCellDecimalConfig(type, currentRange) {
        this.setCellConfig({ dp: type }, currentRange);
    }
    /**
     * 设置单元格config
     * @param config
     * @param currentRange
     */
    setCellConfig(config, currentRange) {
        for (let i = 0; i < currentRange.length; i++) {
            const rangeAllCell = currentRange[i].getAll(); // 得到选中单元格的数组 [CellCoords, CellCoords, CellCoords, CellCoords]
            for (let j = 0; j < rangeAllCell.length; j++) {
                const coords = rangeAllCell[j];
                if (coords.row < 0 || coords.col < 0) {
                    continue;
                }
                const cellMeta = this.hot.getCellMeta(coords.row, coords.col);
                const merge_config = { ...cellMeta.config, ...config };
                for (let item in merge_config) {
                    this.setCellLogic(cellMeta, item, {
                        row: coords.row,
                        col: coords.col,
                        key: item,
                        val: cellMeta.custom?.[item] === merge_config[item]
                            ? null
                            : merge_config[item],
                    });
                }
                // const renderFunc = hotRef.current.getCellRenderer(
                //   coords.row,
                //   coords.col
                // );
                // renderFunc();
            }
        }
        this.hot.render();
    }
    /**
     * 设置属性单元格类型判断
     */
    setCellLogic(cellMeta, item, param) {
        const cellType = cellMeta.type;
        const { row, col, key, val } = param;
        //缩进必须是文本
        if (item === "r" && cellType !== "text") {
            return;
        }
        //操作小数位必须是数字
        if (item === "dp" && cellType !== "numeric") {
            return;
        }
        //逻辑处理后的值
        let value = val;
        if (item === "dp") {
            const cell_dp = cellMeta.custom?.dp === undefined ? 2 : cellMeta.custom?.dp;
            if (val === "add") {
                if (cell_dp < 4) {
                    value = cell_dp + 1;
                }
                else {
                    value = cell_dp;
                }
            }
            if (val === "minus") {
                if (cell_dp < 1) {
                    value = 0;
                }
                else {
                    value = cell_dp - 1;
                }
            }
        }
        this.setCellMetaCustomInfo(row, col, key, value);
    }
    clearCellMetaCustomInfo(keys, cellMetaData) {
        for (let i = 0; i < cellMetaData?.length; i++) {
            const cellMeta = cellMetaData[i];
            if (cellMeta.custom) {
                for (let j = 0; j < keys.length; j++) {
                    const key = keys[j];
                    delete cellMetaData[i].custom[key];
                }
            }
        }
    }
    /**
     * 设置自定义样式
     * @param row
     * @param col
     * @param key
     * @param value
     */
    setCellMetaCustomInfo(row, col, key, value, ref, isSaveMemory) {
        const getCellMeta = this.hot.getCellMeta(row, col);
        let new_custom = {};
        let _this = this;
        if (!getCellMeta["custom"]) {
            if (value === null) {
                new_custom = {};
            }
            else {
                new_custom = {
                    [key]: value,
                };
            }
        }
        else {
            const custom = getCellMeta["custom"];
            if (value === null) {
                delete custom[key];
                new_custom = custom;
            }
            else {
                new_custom = {
                    ...custom,
                    [key]: value,
                };
            }
        }
        if (ref) {
            _this = ref;
        }
        if (isSaveMemory) {
            const memoryCellsMeta = this.getCellMateDataByRowAndProp(row, col, _this.cellMetaData);
            if (!memoryCellsMeta && value !== null) {
                _this.cellMetaData.push({
                    row,
                    col,
                    custom: new_custom,
                });
            }
            else if (memoryCellsMeta && memoryCellsMeta["custom"]) {
                const current_custom = memoryCellsMeta["custom"];
                if (value === null) {
                    delete current_custom[key];
                }
                memoryCellsMeta["custom"] = {
                    ...current_custom,
                    ...new_custom,
                };
            }
        }
        _this.hot.setCellMeta(row, col, "custom", new_custom);
    }
    /**
     * 根据属性字段查询并返回列的索引号
     * key 要查询的config字段
     * value 该字段等于的值
     */
    getColumnIndexByConfig(key, value) {
        let match = [];
        const header_column = this.headerService.headerColumn;
        for (let i = 0; i < header_column.length; i++) {
            const header = header_column[i];
            if (header["config"] &&
                header["config"][key] &&
                header["config"][key] === value) {
                match.push({
                    index: i,
                    item: header,
                });
            }
        }
        return match;
    }
    /**
     * 根据列数据算出组头的位置
     * @param columnData
     */
    getHeaderGroupInfo(columnData) {
        let groupHeader = Array.from(new Set(columnData));
        //生成分组,组头以及顺序
        let headerGroup = [];
        for (let i = 0; i < columnData.length; i++) {
            const text = columnData[i];
            const groupQueIndex = groupHeader.indexOf(text);
            if (groupQueIndex > -1) {
                headerGroup.push({
                    index: i,
                    text: text,
                });
                groupHeader.splice(groupQueIndex, 1);
            }
        }
        return headerGroup;
    }
    /**
     * 设置行配置
     */
    setRowConfig(row, param, iGridData) {
        //优:保持context持有的data保持数据同步，因为gridHooks中会用到
        const gridData = iGridData ? iGridData.data : this.context.data;
        const rowData = gridData[row];
        //CpasTable最少一行数据所以可以用data[0].length来取最后一列
        const rowConfigIndex = iGridData
            ? iGridData.data[0].length - 1
            : this.headerService.lastHeader;
        let config = rowData?.[rowConfigIndex];
        if (config) {
            config = JSON.parse(config);
        }
        let newConfig = {
            ...config,
            ...param,
        };
        if (rowData) {
            rowData[rowConfigIndex] = JSON.stringify(newConfig);
        }
        //如果外部传入了IGridData只是为了处理数据，不需要更新数据
        if (!iGridData) {
            this.hot.updateData(gridData);
        }
    }
    /**
     * 隐藏映射关系以及配置列信息
     */
    hiddenColumnAndRow() {
        if (this.hot) {
            const hiddenIndex = [];
            this.headerService.headerColumn.filter((item, index) => {
                const { config } = item;
                if (config.hidden) {
                    hiddenIndex.push(index);
                }
            });
            if (this.context.isShowMaps) {
                this.hot.updateSettings({
                    nestedHeaders: this.headerService.data,
                    hiddenColumns: {
                        // set columns that are hidden by default
                        columns: [this.headerService.lastHeader].concat(hiddenIndex),
                    },
                    hiddenRows: {
                        rows: [],
                    },
                });
            }
            else {
                this.hot.updateSettings({
                    nestedHeaders: this.headerService.data,
                    hiddenColumns: {
                        // set columns that are hidden by default
                        columns: [0, this.headerService.lastHeader].concat(hiddenIndex),
                    },
                    hiddenRows: {
                        rows: [0],
                    },
                });
            }
        }
    }
    /**
     * 执行分组逻辑
     */
    generateGroup(currentGroupKeyColumn) {
        const columnData = this.hot.getDataAtCol(currentGroupKeyColumn);
        const headerGroup = this.getHeaderGroupInfo(columnData);
        let rOrderByGroup = [];
        // let orderCount = 0;
        //设置组内行的样式，以及自动打入组标签;
        for (let j = 0; j < headerGroup.length; j++) {
            const headerGroupItem = headerGroup[j];
            const headerGroupIndex = headerGroupItem["index"];
            rOrderByGroup.push(headerGroupItem.index);
            for (let i = 0; i < columnData.length; i++) {
                const columnName = columnData[i];
                if (headerGroupItem.text === columnName && i !== headerGroupIndex) {
                    rOrderByGroup.push(i);
                }
            }
        }
        const sheetId = this.hyper.getSheetId("main");
        //操作hyper数据前，先进行一下原值覆盖. 插行插列的时候会有隐藏列同步不过去的情况.
        this.hyper.setSheetContent(0, this.hot.getData());
        //重排移动
        let moved = [];
        for (let i = 0; i < rOrderByGroup.length; i++) {
            let startIndex = rOrderByGroup[i];
            const reOrderIndex = rOrderByGroup[i];
            for (let j = 0; j < moved.length; j++) {
                const moveItem = moved[j];
                if (moveItem > reOrderIndex) {
                    startIndex = startIndex + 1;
                }
            }
            if (i !== startIndex) {
                console.log(`${startIndex} -> ${i}`);
                this.hyper.moveRows(sheetId, startIndex, 1, i);
                moved.push(rOrderByGroup[i]);
            }
        }
        this.hot.loadData(this.hyper.getAllSheetsSerialized()["main"]);
        console.log("-----------rOrderByGroup------------------");
        console.log(rOrderByGroup);
        const reorderColumnData = this.hot.getDataAtCol(currentGroupKeyColumn);
        const reorderHeaderGroup = this.getHeaderGroupInfo(reorderColumnData);
        let count = 0;
        for (let i = 0; i < reorderHeaderGroup.length; i++) {
            const groupInfo = reorderHeaderGroup[i];
            const rowIndex = groupInfo["index"] + count;
            reorderHeaderGroup[i] = { index: rowIndex, text: groupInfo.text };
            const text = groupInfo["text"];
            const config = {
                groupHeader: true,
                groupIndex: rowIndex,
                groupTitle: text,
            };
            this.hot.batch(() => {
                //插入组头
                this.hot.alter("insert_row", rowIndex);
                count++;
                //设置组头内容,以及设置行配置为组头信息
                this.hot.setDataAtCell([[rowIndex, currentGroupKeyColumn, text]]);
            });
            this.setRowConfig(rowIndex, {
                ...config,
                readOnly: true,
                className: "cpas-handson-group-bg",
            });
            // hotRef.current.setCellMeta(rowIndex, currentKeyWord, "readOnly", true);
            // hotRef.current.setCellMeta(
            //   rowIndex,
            //   currentKeyWord,
            //   "className",
            //   "cpas-handson-group-bg"
            // );
        }
        const reorderByGroupHeader = this.hot.getDataAtCol(currentGroupKeyColumn);
        //根据排序后的结果自动打组标签
        for (let j = 0; j < reorderHeaderGroup.length; j++) {
            const headerGroupItem = reorderHeaderGroup[j];
            const headerGroupIndex = headerGroupItem["index"];
            for (let i = 0; i < reorderByGroupHeader.length; i++) {
                const columnName = reorderByGroupHeader[i];
                if (headerGroupItem.text === columnName && i !== headerGroupIndex) {
                    //设置缩进样式
                    this.setCellMetaCustomInfo(i, currentGroupKeyColumn, "r", 2);
                    //打入组标签
                    this.tagService.setRowTags(`${columnName}-组`, [i]);
                    this.setRowConfig(i, {
                        groupIndex: headerGroupIndex,
                    });
                }
            }
        }
        return reorderHeaderGroup;
        // cellMetaDataRef.current = hotRef.current.getCellsMeta();
    }
    /**
     * data中rmap是否重复,返回重复项目列数据
     */
    getDataByRmapRepeat(data, isOriginal = false) {
        if (!data || !data.length) {
            return;
        }
        let tempData = []; //非重复数据,临时暂存
        let repeatData = []; //重复的数据
        for (let i = 0; i < data.length; i++) {
            const rowsData = data[i];
            const rmap = rowsData[0];
            if (rmap && rmap !== "..." && rmap !== "......") {
                tempData.push({
                    index: i,
                    key: rmap,
                    projectCol: rowsData[1], //项目列
                });
            }
        }
        for (let i = 0; i < data.length; i++) {
            const rowsData = data[i];
            const rmap = rowsData[0];
            let values = [];
            //rmap为空或者是三个点，6个点..., ......不检测
            if (rmap && rmap !== "..." && rmap !== "......") {
                const isRepeat = tempData.filter((item) => item.key === rmap);
                const isContain = repeatData.filter((item) => item.key === rmap);
                if (isRepeat && isRepeat.length > 1 && !isContain.length) {
                    let indexs = [];
                    for (let j = 0; j < isRepeat.length; j++) {
                        const index = isOriginal
                            ? isRepeat[j].index
                            : isRepeat[j].index + 1;
                        indexs.push(index);
                        values = values.concat(isRepeat[j].projectCol);
                    }
                    repeatData.push({
                        index: indexs,
                        key: rmap,
                        projectCol: values, //项目列
                    });
                }
            }
        }
        return repeatData;
    }
    /**
     * 计算动态生成的表格高度
     */
    computerTableHeight(iGridData) {
        const padding = 20;
        const columnHeaderHeight = this.context.columnHeaderHeight;
        const rowHeights = this.context.rowHeights;
        console.log("computerTableHeight:", iGridData);
        if (!iGridData || iGridData.data.length === 0) {
            return columnHeaderHeight + rowHeights;
        }
        const { computerLevelData } = this.headerService.headerComputeData(iGridData.header);
        const headerLevel = computerLevelData.length;
        const columnHeaderTotalHeight = columnHeaderHeight * headerLevel;
        const rowCount = iGridData.data.length - 1;
        const rowTotolHeight = rowCount * rowHeights;
        const tableHeight = columnHeaderTotalHeight + rowTotolHeight;
        return tableHeight + padding;
    }
}
//动态计算初始化表高度
// initTableHeightCount(): boolean {
//   if (this.containerRef.current) {
//     const dom = this.containerRef.current;
//
//     //是否初始化的时候就已经计算上工具条的位置了, 如果是render的时候就不需要计算了
//     if (this.props.isShowMenuToolBar) {
//       this.toolBarIsInit = true;
//     }
//
//     //动态获取topbar和bottombar高度
//     if (this.props.topBar) {
//       this.topBarHeight = dom.parentElement
//         .querySelector(".cpas-table-top-bar")
//         .getBoundingClientRect().height;
//     }
//     if (this.props.bottomBar) {
//       this.bottomBarHeight = dom.parentElement
//         .querySelector(".cpas-table-bottom-bar")
//         .getBoundingClientRect().height;
//     }
//     this.tableHeight = dom.getBoundingClientRect().height;
//     if (this.tableHeight === 0 && this.maxHeightError < 3) {
//       console.log(
//         `-------------cpas table init 没有高度停止初始化容错尝试${this.maxHeightError}----------------`
//       );
//       //HandsonTable自身的在页签中的bug. 容错处理100ms后重载尝试
//       setTimeout(() => {
//         this.init(this.containerRef.current);
//       }, 100);
//       this.maxHeightError++;
//
//       return false;
//     }
//     this.tableHeight =
//       this.tableHeight - this.topBarHeight - this.bottomBarHeight;
//
//     //为了兼容handsonTable在tab页签的问题
//     if (this.tableHeight > 0) {
//       if (this.props.tabGroup) {
//         window.sessionStorage.setItem(
//           this.props.tabGroup,
//           this.tableHeight.toString()
//         );
//       }
//     }
//     if (this.tableHeight === 0 && this.props.tabGroup) {
//       const tabContentHeight = window.sessionStorage.getItem(
//         this.props.tabGroup
//       );
//       this.tableHeight = parseFloat(tabContentHeight);
//     }
//   }
//   return true;
// }
// renderHeight() {
//   //目前额外的总高度
//   const externHeight =
//     (this.state.isShowFormulaToolBar ? this.formulaHeight : 0) +
//     (this.props.isShowMenuToolBar && !this.toolBarIsInit
//       ? this.toolBarMargin + this.toolBarHeight
//       : 0);
//   const computedHeight = this.tableHeight - externHeight;
//   this.hot.updateSettings({
//     height: computedHeight,
//   });
// }
